require('dotenv').config()

const amqp = require('amqplib')
const co = require('co')
const nodeMailer = require('nodemailer')

const q = process.env.QUEUE_NAME
const smtpConfig = {
  host: process.env.MAIL_HOST,
  port: process.env.MAIL_PORT,
  // secure: true, // use SSL will cause error
  auth: {
    user: process.env.MAIL_USER,
    pass: process.env.MAIL_PASSWORD,
  }
}

const transporter = nodeMailer.createTransport(smtpConfig)

console.log(q)

co(function* () {
  const conn = yield amqp.connect(amqp.connect('amqp://localhost'))
  const ch = yield conn.createChannel()

  ch.assertQueue(q, { durable: false })

  ch.consume(q, (msg) => {
    const mailOption = {
      from: '"Fred Foo 👥" <' + process.env.MAIL_USER + '>', // sender address
      to: msg.content.toString(), // list of receivers seperatored by `, `
      subject: 'Hello ✔', // subject line
      html: '<b>Hello world 🐴</b>', // html body
    }

    transporter.sendMail(mailOption, (err, message) => {
      if (err) {
        console.error(err)
        return
      }
      // simulate long time delay
      // require('sleep').sleep(5)
      let response = rpcEmail(msg.content.toString())
      ch.sendToQueue(
        msg.properties.replyTo,
        new Buffer(JSON.stringify(response)),
        { correlationId: msg.properties.correlationId }
      )
    })
  })
})

function fib(n) {
  // Do it the ridiculous, but not most ridiculous, way. For better,
  // see http://nayuki.eigenstate.org/page/fast-fibonacci-algorithms
  var a = 0, b = 1;
  for (var i=0; i < n; i++) {
    var c = a + b;
    a = b; b = c;
  }
  return a;
}
function rpcEmail(email) {
  return {
    err: false,
    msg: 'go to ' + email,
  }
}
